package com.multicampus.simplewiki.ctrl;

import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import com.multicampus.simplewiki.model.Document;
import com.multicampus.simplewiki.vo.RestSearchResultVO;
import com.multicampus.simplewiki.vo.SearchListVO;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;

public class RestServiceManager {
	private static final String NAVER_OPENAPI_URL = "http://openapi.naver.com/search";
	private static final String NAVER_KEY = "?key=ae678bc3777d1df07bdcd3a52acaf9a3";
	private static final String NAVER_TARGET = "&target=webkr";
	private static final String NAVER_START = "&start=1";
	private static final String NAVER_DISPLAY = "&display=3";
	
    public SearchListVO<RestSearchResultVO> getNaverSearch(Document document) {
    	
    	SearchListVO<RestSearchResultVO> searchListVO = null;
    	
    	try {
    		String searchKeyword = document.getTitle();

    		System.out.println("======naver keyword : " + searchKeyword);
    		
    		StringBuffer naverQuery = new StringBuffer();
    		naverQuery.append(NAVER_OPENAPI_URL).append(NAVER_KEY)
    			.append(NAVER_TARGET).append(NAVER_START).append(NAVER_DISPLAY);
    		naverQuery.append("&query=").append(searchKeyword);
    		
    		SyndFeedInput input = new SyndFeedInput();
    		SyndFeed feed = input.build(new XmlReader(new URL(naverQuery.toString())));

    		Iterator<SyndEntry> it = feed.getEntries().iterator();
    		
    		searchListVO = new SearchListVO<RestSearchResultVO>();
    		Collection<RestSearchResultVO> results = new ArrayList<RestSearchResultVO>();
    		RestSearchResultVO resultVO = null;
    		SyndEntry entry = null;
    		
            for ( int i=0 ; it.hasNext() ; i++ ) {
            	entry = it.next();
            	resultVO = new RestSearchResultVO();
            	resultVO.setTitle(entry.getTitle());
            	resultVO.setLink(entry.getLink());
            	resultVO.setDescription(entry.getDescription().getValue());
            	results.add(resultVO);
            }
            searchListVO.setSearchResults(results);

        } catch (Exception ex) {
            ex.printStackTrace();
            System.out.println("ERROR: "+ex.getMessage());
        }
        return searchListVO;
    }
}
